<?php
namespace app\admin\controller;

use app\admin\model\AlbumImgModel;
use app\common\model\project_model\AlbumModel;
use app\common\model\project_model\SystemMusicModel;
use app\common\model\project_model\AlbumSkinModel;
use app\common\model\WechatAppletModel;
use app\common\model\WechatUserModel;
use app\yxwadmin\controller\Admin;
use app\admin\model\validate\Album as ValidateAlbum;
use think\Db;
use think\Exception;

class Album extends Admin
{

    public $error_msg = '';

    /**
     * 首页
     * @return string
     * @throws \think\Exception
     */
    public function index()
    {
        // 小程序
        $appletM = new WechatAppletModel();
        $appletD = $appletM->field('id, name')->where(['product_code' => 'photo_albums_bless'])->select();
        $this->assign('applet_list', $appletD);
        return $this->view->fetch();
    }

    /**
     * 初始化表格
     * 关键字搜索
     * 分页
     * @throws
     * @return mixed
     */
    public function getList()
    {
        $limit = input('limit','0');
        $offset = input('offset','0');
        $sortName = input('sortName','id');
        $sortOrder = input('sortOrder','desc');
        $keyword = input('keywords','');
        $applet_id = input('applet_id', '');
        if ($applet_id) {
            $where['applet_id'] = $applet_id;
        } else {
            $where = '1=1';
        }

        $model = new AlbumModel();
        if ($keyword) {
            $count = $model->where($where)->where('open_id|title|skin|content|music_name|share_title', 'like', '%' . $keyword . '%')->count();
            $list = $model
                ->where($where)
                ->where('open_id|title|skin|content|music_name|share_title', 'like', '%' . $keyword . '%')
                ->order([$sortName => $sortOrder])
                ->limit($offset . ',' . $limit)
                ->select();
        } else {
            $count = $model->where($where)->count(); //查询满足要求的总记录数
            $list = $model
                ->where($where)
                ->order(array($sortName=>$sortOrder))
                ->limit($offset.','.$limit)
                ->select();
        }

        $data['total'] = $count;
        $data['rows'] = $list;
        return $data;
    }

    public function add() {
        if (request()->isPost()) {
            $validate = new ValidateAlbum();
            $data = $_REQUEST;
            $data['created_time'] = date('Y-m-d H:i:s', time());
            $data['updated_time'] = date('Y-m-d H:i:s', time());
            $res = $validate->check($data);
            if (!$res) {
                $this->error_msg = $validate->getError();
                return json(['code' => 0, 'msg' => $this->error_msg, 'data' => null]);
            }
            Db::startTrans();
            try {
                $model = new AlbumModel($data);
                $res = $model->allowField(true)->save();
                if (!$res) {
                    throw new Exception($model->getError());
                }
                // 相册图片新增
                $albumImgM = new AlbumImgModel();
                if (!$res = $albumImgM->createAll($model->id, $data['album_img'])) {
                    throw new Exception($albumImgM->err_msg);
                }
                Db::commit();
                return json(['code' => 1, 'msg' => '新增成功', 'data' => null]);
            }catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 0, 'msg' => $e->getMessage(), 'data' => null]);
            }
        } else {
            $this->assign('is_show_list', AlbumModel::isShowList());
            $this->assign('is_system_list', AlbumModel::isSystemList());
            $this->assign('is_verify_list', AlbumModel::isVerifyList());
            $this->assign('applet_list', WechatUserModel::getAppletList());
            $this->assign('music_list', SystemMusicModel::musicList2());
            $this->assign('skin_list', AlbumSkinModel::skinList());
            return $this->fetch();
        }
    }

    public function edit() {
        $id = $_REQUEST['id'];
        $model = new AlbumModel();

        if (request()->isPost()) {
            $validate = new ValidateAlbum();
            $data = $_REQUEST;
            $data['updated_time'] = date('Y-m-d H:i:s', time());
            $res = $validate->check($data);
            if (!$res) {
                $this->error_msg = $validate->getError();
                return json(['code' => 0, 'msg' => $this->error_msg, 'data' => null]);
            }
            Db::startTrans();
            try {
                $model = new AlbumModel();
                $res = $model->allowField(true)->save($data, true);
                if (!$res) {
                    throw new Exception($model->getError());
                }
                // 相册图片新增
                $albumImgM = new AlbumImgModel();
                if (!$res = $albumImgM->createAll($model->id, $data['album_img'], 1)) {
                    throw new Exception($albumImgM->err_msg);
                }
                Db::commit();
                return json(['code' => 1, 'msg' => '修改成功', 'data' => null]);
            }catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 0, 'msg' => $e->getMessage(), 'data' => null]);
            }
        } else {
            $imgM = new AlbumImgModel();
            $this->assign('album_img_list', $imgM->getImg($id));
            $this->assign('is_show_list', AlbumModel::isShowList());
            $this->assign('is_system_list', AlbumModel::isSystemList());
            $this->assign('is_verify_list', AlbumModel::isVerifyList());
            $this->assign('applet_list', WechatUserModel::getAppletList());
            $this->assign('music_list', SystemMusicModel::musicList2());
            $this->assign('skin_list', AlbumSkinModel::skinList());
            $Rs = $model->where(['id' => $id])->find();
            $this->assign('Rs', $Rs);
            return $this->fetch();
        }
    }


    public function view() {
        $id = input('id/d');
        $model = new AlbumModel();
        $Rs = $model->where(['id' => $id])->find();
        $this->assign('Rs', $Rs);
        return $this->fetch();
    }

    /**
     * 审核
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function lock()
    {
        $id = input('id/d');
        $model = new AlbumModel();
        $where = ['id'=>$id];
        $data = $model->where($where)->find();
        if ($data['is_show'] == AlbumModel::IS_SHOW_NO) {
            return json(['code' => 0, 'msg' => '请先发表！']);
        }

        $status = AlbumModel::IS_VERIFY_NO;
        if ($data['is_verify'] == AlbumModel::IS_VERIFY_NO) {
            $status = AlbumModel::IS_VERIFY_YES;
        }
        $res = $model->save(['is_verify' => $status], $where);
        if ($res) {
            $ret['code']=1;
            $ret['msg']='操作成功';
        } else {
            $ret['code']=0;
            $ret['msg']='服务器繁忙';
        }
        return json($ret);
    }

    /**
     * 发布
     *
     * @return \think\response\Json
     * @throws \think\Exception
     */
    public function show()
    {
        $id = input('id/d');
        $model = new AlbumModel();
        $where = ['id'=>$id];
        $data = $model->where($where)->find();

        if ($data['is_system'] == AlbumModel::IS_SYSTEM_NO) {
            return json(['code' => 0, 'msg' => '用户相册，您无权操作！']);
        }

        $status = AlbumModel::IS_SHOW_NO;
        if ($data['is_show'] == AlbumModel::IS_SHOW_NO) {
            $status = AlbumModel::IS_SHOW_YES;
            $up = ['is_show' => $status];
        } else {
            $up = ['is_show' => $status , 'is_verify' => AlbumModel::IS_VERIFY_NO];
        }
        $res = $model->save($up, $where);
        if ($res) {
            $ret['code']=1;
            $ret['msg']='操作成功';
        } else {
            $ret['code']=0;
            $ret['msg']='服务器繁忙';
        }
        return json($ret);
    }

}